package dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import util.Conversion;

import dto.CategoryDTO;
import dto.TemplateCategoryDTO;
import dto.TemplateDTO;
import entities.TemplateCategory;

/**
 * Session Bean implementation class TemplateCategoryDAO
 */
@Stateless
public class TemplateCategoryDAO implements TemplateCategoryDAORemote {
	
	@PersistenceContext
	EntityManager em;
	Conversion converter = new Conversion();
    /**
     * Default constructor. 
     */
    public TemplateCategoryDAO() {
        // TODO Auto-generated constructor stub
    }
    
	public List<TemplateCategoryDTO> getTemplateCategoryListByCategory(CategoryDTO cat) {
		TypedQuery<TemplateCategory> query = em.createQuery(
				"SELECT tc FROM TemplateCategory tc WHERE tc.category.id = :cid",
				TemplateCategory.class);
		List<TemplateCategory> resultList = query.setParameter("cid", cat.getId()).getResultList();

		List<TemplateCategoryDTO> tcList = new ArrayList<TemplateCategoryDTO>();
		
		try {

			for (TemplateCategory tc : resultList) {
				tcList.add(converter.fromTemplateCategoryToTemplateCategoryDTO(tc));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return tcList;
		
	}
	
	public List<TemplateCategoryDTO> getTemplateCategoryListByTemplate(TemplateDTO temp) {
		TypedQuery<TemplateCategory> query = em.createQuery(
				"SELECT tc FROM TemplateCategory tc WHERE tc.template.id = :tid",
				TemplateCategory.class);
		List<TemplateCategory> resultList = query.setParameter("tid", temp.getId()).getResultList();
		List<TemplateCategoryDTO> tcList = new ArrayList<TemplateCategoryDTO>();	
		try {
			for (TemplateCategory tc : resultList) {
				tcList.add(converter.fromTemplateCategoryToTemplateCategoryDTO(tc));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return tcList;		
	}

}
